<?php

declare(strict_types=1);

namespace app\index\controller;

use app\model\Category;
use app\model\Post as ModelPost;
use app\model\PostCollect;
use app\model\PostCommentAttitude;
use app\model\base\WeeklyCount;
use app\model\PostCommentCountWeekly;
use app\model\PostInvite;
use app\model\PostZan;
use app\model\Topic;
use app\model\User;
use app\model\UserRecord;
use think\facade\View;
use think\model\Relation;
use think\Request;

class Post extends Common
{
  public function initialize()
  {
    parent::initialize();

    if (in_array($this->request->action(), [
      'create',
      'save',
      'update',
      'edit',
      'delete',
      'my',
      'collect',
      'optionLike',
      'optionCollect',
    ])) {
      $this->forceLogin();
    }
  }

  /**
   * 显示资源列表
   *
   * @return \think\Response
   */
  public function index()
  {
    //

    $list_index_post = ModelPost::searchPage($this->request);
    $list_comments_posts = PostCommentCountWeekly::order('count desc')->where('week_date', WeeklyCount::parseDate())->limit(10)->select();
    View::assign('list_comments_posts', $list_comments_posts);
    View::assign('list_index_post', $list_index_post);
    return View::fetch();
  }

  public function statusManage()
  {

    $list_post = ModelPost::where('is_verify', $this->request->param('is_verify', 2))
      ->order('sort desc')
      ->order('id desc')
      ->paginate();


    View::assign('list_post', $list_post);
    return View::fetch();
  }

  public function my()
  {

    $target = $this->request->param('target', 'my');

    if ($target == 'my') {
      $model_post = ModelPost::where('user_id', $this->modelUser->id);
    } else if ($target == 'collect') {
      $model_post = ModelPost::hasWhere('collect', ['user_id' => $this->modelUser->id]);
    }

    $list_post = $model_post
      ->order('sort desc')
      ->paginate();

    $list_my_post_count = ModelPost::where('user_id', $this->modelUser->id)->count();
    $list_collect_post_count = PostCollect::where('user_id', $this->modelUser->id)->count();

    View::assign('target', $target);
    View::assign('list_post', $list_post);
    View::assign('list_my_post_count', $list_my_post_count);
    View::assign('list_collect_post_count', $list_collect_post_count);

    return View::fetch();
  }

  /**
   * 显示创建资源表单页.
   *
   * @return \think\Response
   */
  public function create()
  {
    //

    if ($this->modelUser->status == 1) {
      return $this->error('您已被封号');
    }

    $list_category = Category::getListIndexCategory(2);

    View::assign('list_category', $list_category);
    return View::fetch();
  }

  /**
   * 保存新建的资源
   *
   * @param  \think\Request  $request
   * @return \think\Response
   */
  public function save(Request $request)
  {
    //

    $post_data = $request->post();
    $post_data['user_id'] = $this->modelUser->id;
    $post_data['type'] = 2;

    $topic_title = $this->request->param('topic_title');

    if (!empty($topic_title)) {
      $topic_title = trim($topic_title);
      $model_topic = Topic::where('title', $topic_title)->find();

      if (empty($model_topic)) {
        $model_topic = Topic::create([
          'title' => $topic_title
        ]);
      }
      $model_topic->post_count = $model_topic->post_count + 1;

      $model_topic->save();

      $post_data['topic_id'] = $model_topic->id;
    }

    $model_post = ModelPost::create($post_data);

    UserRecord::buildAndSave('new_post', $model_post->id, $this->modelUser->id);

    return $this->success('添加成功', url('Post/read', ['id' => $model_post->id]));
  }

  /**
   * 显示指定的资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function read($id)
  {


    $request = $this->request;

    $model_post = ModelPost::with(['comments' => function (Relation $query) use ($request) {
      $sort_key = $request->param('sort_key', 'zan_balance');
      if ($sort_key == 'zan_balance') {
        $query->order('is_good', 'desc')
          ->order('zan_balance', 'desc')
          ->order('create_time', 'desc');
      } else {
        $query->order($sort_key, $request->param('sort', 'desc'));
      }
    }])->find($id);

    $model_post->readUser = $this->modelUser;


    $list_post = ModelPost::where('status', 1)->order('comment desc')->limit(15)->select();

    View::assign('list_post', $list_post);


    View::assign('post', $model_post);

    return View::fetch();
  }

  public function incHits($id)
  {
    $model_post = ModelPost::find($id);

    $model_post->hits = $model_post->hits + 1;

    $model_post->save();

    return json_message();
  }

  public function optionLike($id, $status)
  {
    PostZan::option($this->modelUser->id, $id, $status);

    return json_message();
  }
  public function optionInvite($post_id, $user_id)
  {

    $model_invite = PostInvite::where('post_id', $post_id)
      ->where('user_id', $user_id)
      ->find();

    if (empty($model_invite)) {
      PostInvite::create([
        'user_id' => $user_id,
        'post_id' => $post_id
      ]);

      // TODO:给用户发消息
    }


    return json_message();
  }
  public function optionCollect($id, $status)
  {
    PostCollect::option($this->modelUser->id, $id, $status);
    return json_message();
  }

  public function optionCommentAttitude($comment_id, $attitude_status)
  {
    $model_comment_attitude = PostCommentAttitude::where('comment_id', $comment_id)
      ->where('user_id', $this->modelUser->id)
      ->find();

    if (empty($model_comment_attitude)) {
      $model_comment_attitude = PostCommentAttitude::create([
        'user_id' => $this->modelUser->id,
        'comment_id' => $comment_id,
        'attitude_status' => $attitude_status
      ]);
    }

    if ($attitude_status == 0) {
      // 减少了一个喜欢或者不喜欢

      if ($model_comment_attitude->attitude_status ==  1) {
        // 本来是喜欢,现在撤销
        $model_comment_attitude->comment->zan--;
      } else if ($model_comment_attitude->attitude_status == 2) {
        // 本来不喜欢,现在撤销了
        $model_comment_attitude->comment->tread--;
      }
    } else if ($attitude_status == 1) {
      // 增加了一个喜欢,但是有可能从不喜欢撤销来的

      if ($model_comment_attitude->attitude_status == 2) {
        // 原来不喜欢,现在喜欢
        $model_comment_attitude->comment->tread--;
      }
      $model_comment_attitude->comment->zan++;
    } else if ($attitude_status == 2) {
      // 增加了一个不喜欢,但是有可能从喜欢撤销来的
      if ($model_comment_attitude->attitude_status == 1) {
        // 原来喜欢,现在不喜欢
        $model_comment_attitude->comment->zan--;
      }
      $model_comment_attitude->comment->tread++;
    }

    $model_comment_attitude->attitude_status = $attitude_status;

    $model_comment_attitude->comment->zan_balance = $model_comment_attitude->comment->zan - $model_comment_attitude->comment->tread;

    $model_comment_attitude->comment->save();
    $model_comment_attitude->save();

    return json_message([
      'zan' => $model_comment_attitude->comment->zan,
      'tread' => $model_comment_attitude->comment->tread,
    ]);
  }

  /**
   * 显示编辑资源表单页.
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function edit($id)
  {
    //
    if ($this->modelUser->status == 1) {
      return $this->error('您已被封号');
    }
    $model_post = ModelPost::find($id);

    View::assign('post', $model_post);

    return View::fetch();
  }

  /**
   * 保存更新的资源
   *
   * @param  \think\Request  $request
   * @param  int  $id
   * @return \think\Response
   */
  public function update(Request $request, $id)
  {
    //

    $post_data = $request->post();

    $model_post = ModelPost::find($id);

    $topic_title = $this->request->param('topic_title');
    if (!empty($topic_title)) {
      $topic_title = trim($topic_title);
      $model_topic = Topic::where('title', $topic_title)->find();

      if (empty($model_topic)) {
        $model_topic = Topic::create([
          'title' => $topic_title
        ]);
      }

      if (!empty($model_post->topic)) {
        if ($model_post->topic->id != $model_topic->id) {
          $model_post->topic->post_count--;
          $model_post->topic->save();

          $model_topic->post_count = $model_topic->post_count + 1;
          $model_topic->save();
        }
      }

      $post_data['topic_id'] = $model_topic->id;
    } else {
      $post_data['topic_id'] = 0;

      if (!empty($model_post->topic)) {
        $model_post->topic->post_count = $model_post->topic->post_count - 1;
        $model_post->topic->save();
      }
    }


    if ($model_post->is_verify == 0) {
      $post_data['is_verify'] = 2;
    }

    $model_post->save($post_data);

    return  $this->success('更新成功', url('Post/read', ['id' => $id]));
  }

  /**
   * 删除指定资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function delete($id)
  {
    //

    ModelPost::destroy($id);

    return json_message();
  }


  public function yaoqing()
  {

    if ($this->request->param('search_type') == 0) {
      $model_user = User::where('status', 0);
    } else if ($this->request->param('search_type') == 1) {
      $model_user = User::where('status', 0);
      $model_user->where('auth_status', 1);
    } else if ($this->request->param('search_type') == 2) {
      // TODO:需要测试
      $model_user = User::hasWhere('friends', ['user_id' => $this->modelUser->id]);
    }
    $model_user->page((int)$this->request->param('page', 1))
      ->limit((int)$this->request->param('limit', 12));


    $model_user->order('id asc');

    $list = $model_user->select();


    View::assign('list', $list);

    return View::fetch();
  }
}
